<template>
  <div
    style="margin: 20px"
    v-loading="loading"
    element-loading-text="正在提交..."
    element-loading-spinner="el-icon-loading"
    class="bg-container"
  >
    <el-form
      ref="form"
      :model="form"
      :rules="rules"
      style="width: 100%; height: fit-content"
      label-width="100px"
      label-position="right"
    >
      <!-- <h2 style="width: 100%; text-align: center; margin-bottom: 50px">
        生产报工
      </h2> -->
      <div class="hander">
        <div class="tit">数字化生产线管理系统-生产报工</div>
        <div class="right">
          <div class="name">
            {{ `${$route.query.jobName}(${$route.query.jobNo})` }}
          </div>
          <div class="out" @click="golayout">退出</div>
        </div>
      </div>
      <div class="form-data">
        <el-row
          class="form-row"
          style="display: flex; justify-content: space-around"
        >
          <el-col class="form-col">
            <el-form-item label="工单：" prop="docNo" :inline-message="true">
              <el-select
                v-model="form.docNo"
                filterable
                placeholder="请选择工单"
                @clear="clearDocNo"
                clearable
                @click="getDocNoList"
                @change="changeDocNo"
                style="width: 100%"
              >
                <el-option
                  @click.native="chooseDocNo(item)"
                  v-for="item in docNoList"
                  :label="item.docNo"
                  :value="item.docNo"
                  :key="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col class="form-col">
            <el-form-item label="品号：">
              <el-input v-model="form.itemCode" disabled style="width: 100%" />
            </el-form-item>
          </el-col>

          <el-col class="form-col">
            <el-form-item
              label="产线："
              prop="productLineId"
              :inline-message="true"
            >
              <el-select
                v-model="form.productLineId"
                @clear="clearLine"
                clearable
                filterable
                placeholder="请选择产线"
                style="width: 100%"
                :disabled="!form.docNo"
              >
                <el-option
                  @click.native="chooseLine(item)"
                  v-for="item in lineList"
                  :label="item.realityLineName"
                  :value="item.id"
                  :key="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <!-- 添加类名form-row -->
          <el-col class="form-col">
            <!-- 添加类名form-col -->
            <el-form-item
              label="车间："
              prop="workshopId"
              :inline-message="true"
            >
              <el-select
                v-model="form.workshopId"
                placeholder="请选择车间"
                @clear="clearWorkshop"
                filterable
                clearable
                style="width: 100%"
                disabled
              >
                <el-option
                  @click.native="workshopChange(item)"
                  v-for="item in workshopList"
                  :key="item.id"
                  :label="item.workshopName"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col class="form-col">
            <el-form-item label="报工时间：" prop="reportTime">
              <el-date-picker
                v-model="form.reportTime"
                type="datetime"
                :picker-options="pickerCurrentTime"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="请选择报工时间"
                :default-value="new Date()"
                style="width: 100%"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row
          class="form-row"
          style="display: flex; justify-content: space-around"
        >
          <el-col class="form-col">
            <el-form-item
              label="工序："
              prop="processId"
              :inline-message="true"
            >
              <el-select
                v-model="form.processId"
                filterable
                @clear="clearProcess"
                clearable
                placeholder="请选择工序"
                style="width: 100%"
                :disabled="!form.productLineId"
              >
                <el-option
                  @click.native="chooseProcess(item)"
                  v-for="item in processList"
                  :label="item.processName"
                  :value="item.processId"
                  :key="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col class="form-col">
            <el-form-item
              label="工位："
              prop="workPositionId"
              :inline-message="true"
            >
              <el-select
                v-model="form.workPositionId"
                filterable
                @clear="clearWorkPosition"
                clearable
                placeholder="请选择工位"
                style="width: 100%"
                :disabled="!form.productLineId"
              >
                <el-option
                  @click.native="chooseWorkstation(item)"
                  v-for="(item, index) in lineDetailsList"
                  :key="index"
                  :label="item.workPositionName"
                  :value="item.workPositionId"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <!-- <el-col  class="form-col">
            <el-form-item
              label="工位："
              prop="processId"
              :inline-message="true"
            >


              <el-select
                v-model="form.workPositionId"
                filterable
                placeholder="请选择工位"
                :disabled="form.processId == null"
                style="width: 100%"
              >
                <el-option
                  v-for="(item, index) in workPositionList"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col> -->
          <el-col class="form-col">
            <el-form-item label="工段：">
              <el-input
                v-model="form.workshopSection"
                disabled
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col class="form-col">
            <el-form-item label="返工数量：" prop="reworkQty">
              <el-input
                v-model="form.reworkQty"
                :min="0"
                style="width: 100%"
                label="请输入返工数量"
                :controls="false"
              ></el-input>
            </el-form-item>
          </el-col>

          <el-col class="form-col">
            <el-form-item
              label="投入工时："
              prop="workhour"
              :inline-message="true"
            >
              <el-input
                v-model="form.workhour"
                :min="0"
                style="width: 100%"
                label="请输入投入工时"
                :controls="false"
              ></el-input>
            </el-form-item>
          </el-col>
          <!--          <el-col  class="form-col">
            <el-form-item label="工位状态："prop="">
              <el-select  v-model="form.moStatus" filterable  placeholder="请选择当前工序状态"  style="width: 100%">
                <el-option
                  v-for="item in options"
                  :label="item.label"
                  :value="item.value"
                  :key="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>-->

          <!-- <el-col class="form-col">
            <el-form-item
              label="在制品完成数量："
              prop="workInProgressQty"
              :inline-message="true"
            >
              <el-input-number
                v-model="form.workInProgressQty"
                :min="0"
                style="width: 100%"
                label="请输入在制品完成数量"
                :controls="false"
              ></el-input-number>
            </el-form-item>
          </el-col>
          <el-col class="form-col">
            <el-form-item
              label="在制品报废数量："
              prop="workInProgressScrapQty"
              :inline-message="true"
            >
              <el-input-number
                v-model="form.workInProgressScrapQty"
                :min="0"
                style="width: 100%"
                label="请输入在制品报废数量"
                :controls="false"
              ></el-input-number>
            </el-form-item>
          </el-col> -->
        </el-row>

        <!-- <el-row
          class="form-row"
          style="display: flex; justify-content: space-around"
        >
          <el-col class="form-col">
            <el-form-item
              label="不良总数："
              prop="badQty"
              :inline-message="true"
            >
              <el-input-number
                v-model="form.badQty"
                :min="0"
                style="width: 100%"
                label="请输入不良总数量"
                :controls="false"
              ></el-input-number>
            </el-form-item>
          </el-col>

          <el-col class="form-col">
            <el-form-item label="工号：">
              <el-input v-model="jobNo" disabled style="width: 100%"></el-input>
            </el-form-item>
          </el-col>
          <el-col class="form-col">
            <el-form-item label="姓名：">
              <el-input
                v-model="jobName"
                disabled
                style="width: 100%"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row> -->
        <el-row
          class="form-row"
          style="display: flex; justify-content: space-around"
        >
        </el-row>
      </div>
    </el-form>
    <div class="table-data">
      <div class="info-t">
        <div class="info-left">
          <div class="item">投入总数: {{ sumNumber }}</div>
          <div class="item">
            完成总数: {{ form.workInProgressQty ? form.workInProgressQty : 0 }}
          </div>
          <div class="item">不良总数: {{ form.badQty ? form.badQty : 0 }}</div>
          <div class="item">
            报废总数:
            {{ form.workInProgressScrapQty ? form.workInProgressScrapQty : 0 }}
          </div>
        </div>
        <div class="info-right">
          <div class="item">产线计划总数:{{planInfo.planQty}}</div>
          <div class="item">产线完成总数:{{planInfo.completeQty}}</div>
          <div class="item">产线剩余总数:{{planInfo.residueQty}}</div>
        </div>
      </div>
      <el-table
        :data="tableData"
        style="width: 100%; margin-bottom: 20px"
        :cell-style="{ 'text-align': 'center', height: '30px' }"
        height="520px"
      >
        <el-table-column label="时间段" fixed width="160">
          <!-- <el-table-column
            label="开始时间"
            prop="startTime"
            width="80"
          ></el-table-column>
          <el-table-column
            label="结束时间"
            prop="endTime"
            width="80"
          ></el-table-column> -->

          <template slot-scope="scope">
            {{ scope.row.startTime }}-{{ scope.row.endTime }}
          </template>
        </el-table-column>
        <el-table-column label="投入数量" width="150" fixed="left">
          <template slot="header">
            <div>投入数量</div>
          </template>
          <template slot-scope="scope">
            <el-input-number
              v-model="scope.row.inputQuantity"
              :min="0"
              placeholder="请输入投入数量"
              disabled
              style="width: 100%"
              :controls="false"
            ></el-input-number>
          </template>
        </el-table-column>
        <el-table-column label="不良数量" width="150" fixed="left">
          <template slot-scope="scope">
            <el-input-number
              v-model="scope.row.badQty"
              :min="0"
              disabled
              placeholder="请输入不良数量"
              style="width: 100%"
              :controls="false"
            ></el-input-number>
          </template>
        </el-table-column>
        <el-table-column label="" fixed="left" width="100">
          <template slot-scope="scope">
            <el-button
              type="primary"
              @click="addDialogItem(scope.row, scope.row.badItem, 'bad')"
              style="width: 100%"
              >添加</el-button
            >
          </template>
        </el-table-column>
        <el-table-column label="报废数量" width="150" fixed="left">
          <template slot-scope="scope">
            <el-input-number
              v-model="scope.row.scrapQty"
              :min="0"
              disabled
              placeholder="请输入报废数量"
              style="width: 100%"
              :controls="false"
            ></el-input-number>
          </template>
        </el-table-column>
        <el-table-column label="" fixed="left" width="100">
          <template slot-scope="scope">
            <el-button
              type="primary"
              @click="addDialogItem(scope.row, scope.row.scrapItem, 'scrap')"
              style="width: 100%"
              >添加</el-button
            >
          </template>
        </el-table-column>
        <!--      <el-table-column label="不良类别">
        <template #header>
          <div class="tab-in-table">
            <el-tabs v-model="activeTab" type="card" @tab-click="handleTabClick">
              <el-tab-pane label="不良类别" name="column1"></el-tab-pane>
              <el-tab-pane label="报废原因" name="column2"></el-tab-pane>
            </el-tabs>
          </div>
        </template>
        <el-table-column v-if="activeTab === 'column1'" v-for="(col, index) in 8" :key="index">
          <template slot="header" >
            <div>
              <el-select v-model="headerSelectData[index]" placeholder="请选择">
                <el-option
                  v-for="item in reworkItems"
                  :label="item.reason"
                  :value="item.reason">
                </el-option>
              </el-select>
            </div>
          </template>
          <template slot-scope="scope">
            <el-input-number v-model="scope.row[`defectiveCategory${index + 1}`]" :min="0" style="width: 100%;" :disabled="!headerSelectData[index]" placeholder="请输入数量"></el-input-number>
          </template>
        </el-table-column>

        <el-table-column v-if="activeTab === 'column2'" v-for="(col, index) in 8" :key="index" >
          <template slot="header">
            <div>
              <el-select v-model="headerSelectScrapData[index]" placeholder="请选择">
                <el-option
                  v-for="item in reworkItems"
                  :label="item.reason"
                  :value="item.reason">
                </el-option>
              </el-select>
            </div>
          </template>
          <template slot-scope="scope">
            <el-input-number v-model="scope.row[`scrapReason${index + 1}`]" :min="0" style="width: 100%;" :disabled="!headerSelectScrapData[index]" placeholder="请输入数量"></el-input-number>
          </template>
        </el-table-column>

      </el-table-column>-->
        <!--      <el-table-column label="报废" fixed="right">
        <template slot="header">
          <div>报废数量</div>
        </template>
        <template slot-scope="scope">
          <el-input-number v-model="scope.row.scrapQty" :min="0" style="width: 100%;" placeholder="请输入报废数量" ></el-input-number>
        </template>
      </el-table-column>-->
        <el-table-column label="异常" fixed="right">
          <template slot="header">
            <div>异常情况</div>
          </template>
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.exception"
              placeholder="请输入异常情况"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column label="产出数量" width="150" fixed="right">
          <template slot="header">
            <div>产出数量</div>
          </template>
          <template slot-scope="scope">
            <el-input-number
              v-model="scope.row.outputQuantity"
              :min="0"
              style="width: 100%"
              placeholder="请输入产出数量"
              :controls="false"
            ></el-input-number>
          </template>
        </el-table-column>
        <el-table-column label="良率" width="150" fixed="right">
          <template slot="header">
            <div>良率</div>
          </template>
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.yieldRate"
              placeholder="请输入良率"
              disabled
            ></el-input>
          </template>
        </el-table-column>
        <!--      <el-table-column label="线长查核" width="110" fixed="right">
        <template slot="header">
          <div>线长查核</div>
        </template>
        <template slot-scope="scope">
          <el-input v-model="scope.row.lineCheck" placeholder="请输入线长查核情况"></el-input>
        </template>
      </el-table-column>-->
      </el-table>
    </div>

    <div class="footer">
      <el-button type="primary" @click="addRow" style="margin-top: 10px"
        >添加</el-button
      >
      <el-button
        type="primary"
        @click="submitData"
        style="margin-top: 10px; margin-left: 30px"
        >提交</el-button
      >
    </div>
    <el-dialog title="添加时间段" :visible.sync="dialogVisible" width="30%">
      <el-form :model="timePeriodForm">
        <el-form-item label="间隔">
          <el-radio-group v-model="timePeriodForm.interval">
            <el-radio label="半小时">半小时</el-radio>
            <el-radio label="一小时">一小时</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="起始时间">
          <el-time-picker
            v-model="timePeriodForm.startTime"
            value-format="HH:mm"
            placeholder="选择起始时间"
            :picker-options="pickerOptions"
          ></el-time-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmAddTimePeriod"
          >确 定</el-button
        >
      </div>
    </el-dialog>

    <el-dialog
      :title="addTitle"
      :visible.sync="addDialogVisible"
      width="50%"
      append-to-body
      :close-on-click-modal="false"
    >
      <div class="el-dialog__body" style="height: 50vh">
        <el-form label-width="80px" class="dialog-form">
          <el-form-item>
            <div class="column-labels">
              <div class="label-item">{{ addReasonLabel }}</div>
              <div
                class="label-item"
                style="text-align: left; padding-left: 50px"
              >
                {{ addQtyLabel }}
              </div>
            </div>
            <div
              v-for="(item, index) in defectItems"
              :key="index"
              class="item-container"
            >
              <el-row class="item-row">
                <el-col :span="12">
                  <el-checkbox-button
                    :label="item.reason"
                    v-model="checkedReasons"
                    class="custom-checkbox-button"
                  >
                    {{ item.reason }}
                  </el-checkbox-button>
                </el-col>
                <el-col :span="12">
                  <el-input-number
                    v-model="item.qty"
                    :disabled="
                      !checkedReasons.includes(item.reason) && item.qty === 0
                    "
                    :min="0"
                    size="medium"
                    style="width: 150px; float: left"
                  />
                </el-col>
              </el-row>
            </div>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button
          type="primary"
          @click="handleAddSubmit"
          style="width: 150px; height: 50px"
          >确定</el-button
        >
        <el-button
          @click="addDialogVisible = false"
          style="width: 150px; height: 50px"
          >取消</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getLineList,
  getRealityProductLineDetailsList,
} from "@/api/pfoc/realityproductlinemain"; //获取产线集合,根据产线ID获取产线工序集合
import {
  getPersonWorkOrderReportInfo,
  saveWorkOrderReport,
} from "@/api/workorder/workorderreport"; //生产报工保存
import { getWorkshopList } from "@/api/pfoc/workshop"; //获取全部车间
import { getWorkScheduleListByLineId } from "@/api/workorder/workscheduling"; //根据产线ID获取产线下生产中的排产工单（暂废弃）
import {
  getDocNoListByLineId,
  getScheduleMainNotCompleted,
  getDocNoLineIdDataInfo,
} from "@/api/workorder/workorderschedulemain"; //根据产线ID获取产线下生产中的排产工单
import { getBadItemByProcessId } from "@/api/pfoc/pfocprocess"; //根据工序Id获取不良项
import { getPersonCredentialList } from "@/api/workorder/personcredentialmanage"; //获取员工信息
import { getObj as lineById } from "@/api/pfoc/realityproductlinemain"; //获取员工信息

export default {
  data() {
    return {
      loading: false,
      activeTab: "column1",
      form: {
        productLineId: null, //产线ID
        productLineName: null, //产线名称
        docNo: null, //工单号
        workshopSection: null, //工段
        itemCode: null, //品号
        reportTime: null, //报工时间
        moStatus: null, //工单当前工序状态
        workInProgressScrapQty: undefined, //报废数量
        workInProgressQty: undefined, //已完成数量
        reworkQty: undefined, //返工数量
        badQty: undefined, //不良数量
        processName: null, //工序名称
        processId: null, //工序ID
        // workstation:null,//工位
        workPositionId: null, //工位ID
        workPositionName: null, //工位名称
        workshopId: null, //车间ID
        workshopName: null, //车间名称
        workhour: undefined, //投入工时
        reportBy: null, //报工人
      },
      processBadItem: [], //存储工序不良项
      lineList: [], //产线集合
      lineInfo: {}, //产线数据对象
      docNoList: [], //工单集合
      workOrderProductionList: [], //产线生产信息
      lineDetailsList: [], //产线详情集合
      processList: [], //工序集合
      workshopList: [], //车间数据集合
      personList: [], //人员信息集合
      badItem: null, //不良项集合
      scrapItem: null, //报废项集合
      options: [
        {
          value: "已完工",
          label: "已完工",
        },
        {
          value: "未完工",
          label: "未完工",
        },
      ],
      rules: {
        // workshopId: [
        //   { required: true, message: "请选择车间", trigger: "change" },
        // ],
        reportTime: [
          { required: true, message: "请选择报工时间", trigger: "change" },
        ],
        productLineId: [
          { required: true, message: "请选择产线", trigger: "change" },
        ],
        docNo: [{ required: true, message: "请选择工单", trigger: "change" }],
        reworkQty: [
          { required: false, message: "请选择返工数量", trigger: "change" },
        ],
        processId: [
          { required: true, message: "请选择工序", trigger: "change" },
        ],
        workInProgressScrapQty: [
          { required: true, message: "请输入在制品报废数量", trigger: "blur" },
        ],
        workInProgressQty: [
          { required: true, message: "请输入在制品完成数量", trigger: "blur" },
        ],
        badQty: [
          { required: true, message: "请输入不良总数量", trigger: "blur" },
        ],
        workhour: [
          { required: true, message: "请输入投入工时", trigger: "blur" },
        ],
        moStatus: [
          { required: true, message: "请选择工位状态", trigger: "change" },
        ],
      },
      tableData: [
        {
          startTime: "08:00",
          endTime: "10:00",
          inputQuantity: undefined,
          badQty: undefined,
          badItem: [],
          scrapQty: undefined,
          scrapItem: [],
          exception: "",
          outputQuantity: undefined,
          yieldRate: "",
          lineCheck: "",
        },

        {
          startTime: "10:00",
          endTime: "12:00",
          inputQuantity: undefined,
          badQty: undefined,
          badItem: [],
          scrapQty: undefined,
          scrapItem: [],
          exception: "",
          outputQuantity: undefined,
          yieldRate: "",
          lineCheck: "",
        },

        {
          startTime: "13:00",
          endTime: "15:00",
          inputQuantity: undefined,
          badQty: undefined,
          badItem: [],
          scrapQty: undefined,
          scrapItem: [],
          exception: "",
          outputQuantity: undefined,
          yieldRate: "",
          lineCheck: "",
        },

        {
          startTime: "15:00",
          endTime: "17:00",
          inputQuantity: undefined,
          badQty: undefined,
          badItem: [],
          scrapQty: undefined,
          scrapItem: [],
          exception: "",
          outputQuantity: undefined,
          yieldRate: "",
          lineCheck: "",
        },

        {
          startTime: "18:00",
          endTime: "20:00",
          inputQuantity: undefined,
          badQty: undefined,
          badItem: [],
          scrapQty: undefined,
          scrapItem: [],
          exception: "",
          outputQuantity: undefined,
          yieldRate: "",
          lineCheck: "",
        },

        {
          startTime: "20:00",
          endTime: "22:00",
          inputQuantity: undefined,
          badQty: undefined,
          badItem: [],
          scrapQty: undefined,
          scrapItem: [],
          exception: "",
          outputQuantity: undefined,
          yieldRate: "",
          lineCheck: "",
        },
      ],
      dialogVisible: false,
      timePeriodForm: {
        interval: "半小时",
        startTime: "20:00",
      },
      pickerOptions: {
        disabledHours() {
          return [
            0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18,
            19,
          ];
        },
        disabledMinutes() {
          return [];
        },
      },
      headerSelectData: Array(8).fill(""),
      headerSelectScrapData: Array(8).fill(""),
      jobNo: null,
      jobName: null,
      infoList: [],
      jobFlg: false,
      addTitle: "",
      defectItems: [],
      checkedReasons: [],
      currentRow: null,
      addDialogVisible: false,
      dialogFlg: null,
      addReasonLabel: null,
      addQtyLabel: null,
      pickerCurrentTime: {
        disabledDate(time) {
          // 只允许选择今天及之前的时间
          return time.getTime() > Date.now();
        },
      },
      workPositionList: [],
      quantityCompletion: 0,
      planInfo:{
        planQty:0,
        completeQty:0,
        residueQty:0,
      }
    };
  },
  watch: {
    //监听表格内容自动计算良率
    tableData: {
      handler(newVal) {
        newVal.forEach((row) => {
          this.calculateYieldRate(row);
        });
        // 重新计算总数
        this.calculateTotals();
      },
      deep: true,
    },
    personList(newValue, oldValue) {
      //通过员工集合判断是否为员工号如果为员工号
      this.personList.forEach((person) => {
        if (person.jobNo === this.jobNo) {
          this.defaultChoose();
        }
      });
    },
    "form.productLineId": {
      handler(val) {
        if (val) {
          this.docNoLineIdDataInfo();
        }else{
          this.planInfo = {
            planQty:0,
            completeQty:0,
            residueQty:0,
          }
        }
      },
    },
  },
  mounted() {
    this.activeTab = "column1";
    this.jobNo = this.$route.query.jobNo;
    this.jobName = this.$route.query.jobName;
    this.getDocNoList();
  },
  created() {
    //获取产线集合
    this.getLineListData();
    //获取车间集合
    this.getWorkshopListData();
    //获取所有员工
    //this.getPersonCredentialListData();
  },
  computed: {
    sumNumber() {
      return this.tableData.reduce((sum, row) => {
        const outputQuantity = parseFloat(row.outputQuantity) || 0;
        const badQty = parseFloat(row.badQty) || 0;
        const scrapQty = parseFloat(row.scrapQty) || 0;
        return sum + outputQuantity + badQty + scrapQty;
      }, 0);
    },
  },
  methods: {
    //产线排产数据
    docNoLineIdDataInfo() {
      getDocNoLineIdDataInfo({
        lineId: this.form.productLineId,
        docNo: this.form.docNo
      }).then((response) => {
        this.planInfo = response.data.data;
      })
    },
    getDocNoList() {
      getScheduleMainNotCompleted().then((response) => {
        this.docNoList = response.data.data;
      });
    },
    changeDocNo(val) {
      this.lineList = [];
      const fItem = this.docNoList.find((item) => item.docNo === val);
      const lineIds = fItem.lineIds.split(",");
      const lineNames = fItem.lineNames.split(",");
      lineIds.forEach((lineId, index) => {
        this.lineList.push({
          id: lineId,
          realityLineName: lineNames[index],
        });
      });
      this.form.workshopId = fItem.workshopId;
      this.clearWorkshop();
    },
    golayout() {
      this.$router.push({
        path: "/login",
      });
    },
    handleTabClick(tab) {
      this.activeTab = tab.name;
    },
    //默认选择
    defaultChoose() {
      getPersonWorkOrderReportInfo(this.jobNo).then((response) => {
        this.infoList = response.data.data;
        //info不为空则取出第一条数据
        if (this.infoList.length > 0) {
          const info = this.infoList[0];
          //取出车间ID以及车间名称
          this.form.workshopId = info.workshopId;
          this.form.workshopName = info.workshopName;
          //取出产线ID以及产线名称
          this.form.productLineId = info.lineId;
          const row = {
            id: info.lineId,
            realityLineName: info.realityLineName,
          };
          this.chooseLine(row);
        }
      });
    },
    addRow() {
      const lastRow = this.tableData[this.tableData.length - 1];
      if (lastRow) {
        this.timePeriodForm.startTime = lastRow.endTime;
      }
      this.dialogVisible = true;
    },
    confirmAddTimePeriod() {
      const { interval, startTime } = this.timePeriodForm;
      let endTime;
      if (interval === "半小时") {
        const start = new Date(`2025-01-06T${startTime}`);
        start.setMinutes(start.getMinutes() + 30);
        endTime = start.toTimeString().slice(0, 5);
      } else {
        const start = new Date(`2025-01-06T${startTime}`);
        start.setHours(start.getHours() + 1);
        endTime = start.toTimeString().slice(0, 5);
      }
      let scrapItem = [];
      let badItem = [];
      //判断this.processBadItem是否为空，不为空则创建新的table对象
      if (!this.validatenull(this.processBadItem)) {
        scrapItem = this.processBadItem.map((item) => ({
          reason: item.reason,
          qty: 0,
        }));
        badItem = this.processBadItem.map((item) => ({
          reason: item.reason,
          qty: 0,
        }));
      }
      this.tableData.push({
        startTime,
        endTime,
        inputQuantity: "",
        badQty: undefined,
        badItem: badItem,
        scrapQty: undefined,
        scrapItem: scrapItem,
        exception: "",
        outputQuantity: "",
        yieldRate: "",
        lineCheck: "",
      });
      this.dialogVisible = false;
    },
    calculateYieldRate(row) {
      const badQty = parseFloat(row.badQty) || 0;
      const scrapQty = parseFloat(row.scrapQty) || 0;
      const outputQuantity = parseFloat(row.outputQuantity) || 0;
      const inputQuantity = outputQuantity + badQty + scrapQty;
      if (
        this.validatenull(row.badQty) &&
        this.validatenull(row.scrapQty) &&
        this.validatenull(row.outputQuantity)
      ) {
        row.inputQuantity = undefined;
      } else {
        row.inputQuantity = inputQuantity;
      }
      if (inputQuantity > 0) {
        row.yieldRate =
          ((outputQuantity / inputQuantity) * 100).toFixed(2) + "%";
      } else {
        row.yieldRate = null;
      }
    },
    calculateTotals() {
      let totalOutput = 0;
      let totalScrap = 0;
      let totalBad = 0;

      this.tableData.forEach((row) => {
        totalOutput += parseFloat(row.outputQuantity) || 0;
        totalBad += parseFloat(row.badQty) || 0;
        totalScrap += parseFloat(row.scrapQty) || 0;
      });

      this.form.workInProgressQty = totalOutput;
      this.form.workInProgressScrapQty = totalScrap;
      this.form.badQty = totalBad;
    },
    submitData() {
      this.form.reportBy = this.jobNo
      const reportData = { ...this.form } //在制品报工数据
      // 统计 el-table 中所有行的总的投入数量和产出数量
      let totalInputQuantity = 0
      let totalOutputQuantity = 0
      this.tableData.forEach((row) => {
        totalInputQuantity += parseFloat(row.inputQuantity) || 0
        totalOutputQuantity += parseFloat(row.outputQuantity) || 0
      })
      //校验报工数量
      if (totalInputQuantity > this.planInfo.residueQty) {
        this.$alert(`当前报工数量（${totalInputQuantity}）大于剩余数量（${this.planInfo.residueQty}），请勿提交大于剩余数量的报工！`,"提示", {
          confirmButtonText: '确定'
        })
        return
      }


      // 整合 el-form 和 el-table 中的数据
      const mainData = {
        //报工主表数据
        ...this.form,
        investQty: totalInputQuantity,
        qualifiedQty: totalOutputQuantity
      }
      const detailsData = [] //报工详情表数据
      const scrapDetailsData = [] //报工详情表数据
      this.tableData.forEach((row) => {
        const {
          startTime,
          endTime,
          inputQuantity,
          exception,
          outputQuantity,
          yieldRate,
          lineCheck
        } = row
        let scrapQty = 0
        let badTotal = 0
        const defectiveCategories = []
        const scrapReasonGroups = []
        //取出badItem数据循环判断qty大于0的放入defectiveCategories中数据存储格式为 defectiveCategories.push({ reason, count: category });
        if (!this.validatenull(row.badItem)) {
          row.badItem.forEach(({ reason, qty }) => {
            if (qty > 0) {
              defectiveCategories.push({ reason, count: qty })
            }
            badTotal += parseFloat(qty) || 0
          })
        }
        if (!this.validatenull(row.scrapItem)) {
          row.scrapItem.forEach(({ reason, qty }) => {
            if (qty > 0) {
              scrapReasonGroups.push({ reason, count: qty })
            }
            scrapQty += parseFloat(qty) || 0
          })
        }
        // 根据不良类别数量生成多条数据
        defectiveCategories.forEach(({ reason, count }) => {
          detailsData.push({
            ...this.form, // 整合 el-form 中的数据
            startTime, //开始时间
            endTime, //结束时间
            investQty: inputQuantity, //投入数量
            badCategory: reason, //不良项
            badQty: count, //不良数量
            abnormalSituation: exception, //异常情况
            outPutQty: outputQuantity, //产出数量
            scrapQty: scrapQty, //报废数量
            yield: yieldRate, //良率
            lineLeaderCheck: lineCheck //线长查核
          })
        })

        // 根据不良类别数量生成多条数据
        scrapReasonGroups.forEach(({ reason, count }) => {
          scrapDetailsData.push({
            ...this.form, // 整合 el-form 中的数据
            startTime, //开始时间
            endTime, //结束时间
            investQty: inputQuantity, //投入数量
            scrapReason: reason,
            scrapQty: count,
            abnormalSituation: exception,
            outPutQty: outputQuantity,
            badQty: badTotal,
            yield: yieldRate,
            lineLeaderCheck: lineCheck //线长查核
          })
        })
      })
      if (totalInputQuantity === 0 || totalOutputQuantity === 0) {
        this.$message.error("请保证最少有一条完整的报工信息")
      }
      this.$refs.form.validate((valid) => {
        if (valid) {
          const t = this
          this.$confirm("是否提交", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          })
            .then(function() {
              t.loading = true
              if (t.validatenull(t.form.workshopId)) {
                t.form.workshopName = null
              }
              if (t.validatenull(t.form.productLineId)) {
                t.form.productLineName = null
              }
              var obj = {
                workorderReport: reportData, //报工表
                workOrderProductionReport: mainData, //报工主表数据
                workOrderReportDetailsList: detailsData, //报工子表数据
                workOrderReportScrapDetailsList: scrapDetailsData
              }

              //调用保存接口
              saveWorkOrderReport(obj)
                .then((response) => {
                  if (response.data.data === "true") {
                    //准备跳工单号
                    //根据当前工单号从docNoList找到下一个工单号对应的对象
                    const currentIndex = t.docNoList.findIndex(
                      (item) => item.docNo === t.form.docNo
                    )
                    if (
                      currentIndex !== -1 &&
                      currentIndex < t.docNoList.length - 1
                    ) {
                      const nextIndex = (currentIndex + 1) % t.docNoList.length
                      // t.form.docNo = t.docNoList[nextIndex].docNo;
                      this.chooseDocNo(t.docNoList[nextIndex])
                    }
                  }

                  t.$message.success("提交成功")
                  //更新排产数据
                  t.docNoLineIdDataInfo()

                  const badItem = t.processBadItem.map((item) => ({
                    reason: item.reason,
                    qty: 0
                  }))

                  const scrapItem = []
                  if (t.processScrapItem != undefined && t.processScrapItem != null) {
                    scrapItem = t.processScrapItem.map((item) => ({
                      reason: item.reason,
                      qty: 0
                    }))
                  }

                  t.tableData = [
                    {
                      startTime: "08:00",
                      endTime: "10:00",
                      inputQuantity: undefined,
                      badQty: undefined,
                      badItem: badItem,
                      scrapQty: undefined,
                      scrapItem: scrapItem,
                      exception: "",
                      outputQuantity: undefined,
                      yieldRate: "",
                      lineCheck: ""
                    },

                    {
                      startTime: "10:00",
                      endTime: "12:00",
                      inputQuantity: undefined,
                      badQty: undefined,
                      badItem: badItem,
                      scrapQty: undefined,
                      scrapItem: scrapItem,
                      exception: "",
                      outputQuantity: undefined,
                      yieldRate: "",
                      lineCheck: ""
                    },

                    {
                      startTime: "13:00",
                      endTime: "15:00",
                      inputQuantity: undefined,
                      badQty: undefined,
                      badItem: badItem,
                      scrapQty: undefined,
                      scrapItem: scrapItem,
                      exception: "",
                      outputQuantity: undefined,
                      yieldRate: "",
                      lineCheck: ""
                    },

                    {
                      startTime: "15:00",
                      endTime: "17:00",
                      inputQuantity: undefined,
                      badQty: undefined,
                      badItem: badItem,
                      scrapQty: undefined,
                      scrapItem: scrapItem,
                      exception: "",
                      outputQuantity: undefined,
                      yieldRate: "",
                      lineCheck: ""
                    },

                    {
                      startTime: "18:00",
                      endTime: "20:00",
                      inputQuantity: undefined,
                      badQty: undefined,
                      badItem: badItem,
                      scrapQty: undefined,
                      scrapItem: scrapItem,
                      exception: "",
                      outputQuantity: undefined,
                      yieldRate: "",
                      lineCheck: ""
                    },

                    {
                      startTime: "20:00",
                      endTime: "22:00",
                      inputQuantity: undefined,
                      badQty: undefined,
                      badItem: badItem,
                      scrapQty: undefined,
                      scrapItem: scrapItem,
                      exception: "",
                      outputQuantity: undefined,
                      yieldRate: "",
                      lineCheck: ""
                    }
                  ]
                  // t.tableData.forEach((row) => {
                  //   row.inputQuantity = undefined;
                  //   row.badQty = undefined;
                  //   row.scrapQty = undefined;
                  //   row.investQty=undefined
                  //   row.badItem = this.processBadItem.map((item) => ({
                  //     reason: item.reason,
                  //     qty: 0,
                  //   }));
                  //   row.scrapItem = this.processBadItem.map((item) => ({
                  //     reason: item.reason,
                  //     qty: 0,
                  //   }));
                  //   row.exception = "";
                  //   row.outputQuantity = undefined;
                  //   row.yieldRate = "";
                  //   row.lineCheck = "";
                  // });
                  t.loading = false
                })
                .catch(() => {
                  t.loading = false
                })
            })
            .catch(() => {
              t.loading = false
            })
        } else {
          return false
        }
      })
    },

    /**获取车间集合*/
    getWorkshopListData() {
      getWorkshopList().then((response) => {
        this.workshopList = response.data.data
      })
    },
    /**车间选择*/
    workshopChange(row) {
      // if (row.workshopName !== this.form.workshopName) {
      //   this.clearWorkshop();
      //   this.form.workshopName = row.workshopName; //车间名称
      // }
    },
    getPersonCredentialListData() {
      getPersonCredentialList().then((response) => {
        this.personList = response.data.data;
      });
    },
    //清除车间
    clearWorkshop() {
      this.form.workshopName = null;
      this.form.realityLineName = null;
      this.form.productLineId = null;
      this.form.workshopId = null;
      this.form.itemCode = null;
      this.form.workshopSection = null;
      this.form.processName = null;
      this.form.processId = null;
      this.form.workPositionId = null; //工位ID
      this.form.workPositionName = null; //工位名称
    },
    //工序清除
    clearProcess() {
      this.initWork();
    },
    //工位清除
    clearWorkPosition() {
      this.initWork();
    },
    //初始化工序、工位
    initWork() {
      if (!this.form.processId && !this.form.workPositionId) {
        this.getList();
      }
    },
    //产线选择
    chooseLine(row) {
      //
      //查询车间数据
      this.workshopList = [];
      lineById(row.id).then((response) => {
        const lineList = response.data.data;
        this.workshopList = [
          {
            id: lineList.workshopId,
            workshopName: lineList.workshopName,
          },
        ];
        this.form.workshopId = lineList.workshopId;
      });
      this.form.productLineId = row.id; //产线ID
      this.form.productLineName = row.realityLineName; //产线名称
      this.lineInfo = { ...row }; //当前选择的产线对象
      this.getList(); //获取当前产线下未完工的排产工单
    },
    //清除产线
    clearLine() {
      this.form.realityLineName = null;
      this.form.productLineId = null;
      // this.form.docNo = null;
      this.form.itemCode = null;
      this.form.workshopSection = null;
      this.form.processName = null;
      this.form.processId = null;
      this.form.workPositionId = null; //工位ID
      this.form.workPositionName = null; //工位名称
    },
    //工单选择
    chooseDocNo(row) {
      this.clearDocNo();
      if (this.validatenull(row.docNo)) {
        this.form.itemCode = null;
      } else {
        this.form.itemCode = row.itemCode;
      }
    },
    //工单清除
    clearDocNo() {
      this.form.itemCode = null;
      this.form.workshopSection = null;
      this.form.processName = null;
      this.form.processId = null;
      this.form.workPositionId = null; //工位ID
      this.form.workPositionName = null; //工位名称
      this.form.productLineId = null; //产线id
      this.form.realityLineName = null; //产线名称
    },
    //获取产线集合
    getLineListData() {
      getLineList().then((response) => {
        this.lineList = response.data.data;
      });
    },
    // 工单排序列表查询
    getList() {
      if (this.validatenull(this.form.productLineId)) {
        this.$message.warning("请选择产线。");
        return;
      }
      this.tableLoading = true;
      //根据产线ID查询产线下未完工的排产工单
      /*   var obj = {
           productionLineId:this.form.productLineId,
           moStatus:"生产中"
         }*/
      // getDocNoListByLineId(this.form.productLineId).then((response) => {
      //   this.docNoList = response.data.data;
      // });
      //根据产线ID获取产线详情
      getRealityProductLineDetailsList(this.form.productLineId).then(
        (response) => {
          var data = response.data.data;
          //子表数据 //产线详情集合-去重
          const map = new Map();
          this.lineDetailsList = data.realityProductLineDetailsList
            .filter((item) => item.workPositionId != null)
            .filter(
              (item) =>
                !map.has(item["workPositionId"]) &&
                map.set(item["workPositionId"], true)
            );

          this.processList = data.realityProductLineDetailsList;
          if (this.infoList.length > 0 && !this.jobFlg) {
            this.jobFlg = true;
            const info = this.infoList[0];
            // this.form.workPositionId = info.workPositionId;
            //找到this.lineDetailsList对应的workPositionId对象
            for (let i = 0; i < this.lineDetailsList.length; i++) {
              if (this.lineDetailsList[i].processId === info.processId) {
                this.form.processId = info.processId;
                //从info中获取工序ID并从processList找到对应的对象
                for (let i = 0; i < this.processList.length; i++) {
                  if (this.processList[i].processId === info.processId) {
                    this.chooseProcess(this.processList[i]);
                    break;
                  }
                }
                break;
              }
            }
          }
        }
      );
    },
    //工位选择
    chooseWorkstation(row) {
      const map = new Map();
      this.processList = this.processList
        .filter(
          (item) =>
            item.workPositionId != null &&
            row.workPositionId == item.workPositionId
        )
        .filter(
          (item) =>
            !map.has(item["processId"]) && map.set(item["processId"], true)
        );
      return;

      if (this.form.workPositionName !== row.workPositionName) {
        this.form.workPositionName = row.workPositionName; //工位名称
        this.processList = JSON.parse(row.workPositionProcessItem);
        // this.form.processName = null;
        // this.form.processId = null;
        // this.form.workshopSection = null;
      }
    },
    //工序选择
    chooseProcess(row) {
      this.form.workshopSection = row.workshopSection;
      this.form.processName = row.processName;
      this.form.processId = row.processId;

      //工位去重判断
      const map = new Map();
      this.lineDetailsList = this.processList
        .filter(
          (item) =>
            item.workPositionId != null && row.processId == item.processId
        )
        .filter(
          (item) =>
            !map.has(item["workPositionId"]) &&
            map.set(item["workPositionId"], true)
        );
      //根据工序ID查询不良项
      getBadItemByProcessId(row.processId).then((response) => {
        this.badItem = null;
        this.badItem = response.data.data.badItem;
        this.scrapItem = response.data.data.scrapItem;
        this.form.workshopSection = response.data.data.workshopSection;
        if (!this.validatenull(this.badItem)) {
          const items = this.badItem.split(",");
          this.processBadItem = items.map((item) => ({ reason: item }));
          //将this.processBadItem中的reason放入this.table中的scrapItem中与badItem集合中，并且两个集合中是对象，对象包括reason与qty两个字段
          this.tableData.forEach((row) => {
            row.badItem = this.processBadItem.map((item) => ({
              reason: item.reason,
              qty: 0,
            }));
          });
        } else {
          this.tableData.forEach((row) => {
            row.badItem = [];
          });
        }
        if (!this.validatenull(this.scrapItem)) {
          const items = this.scrapItem.split(",");
          this.processScrapItem = items.map((item) => ({ reason: item }));
          this.tableData.forEach((row) => {
            row.scrapItem = this.processScrapItem.map((item) => ({
              reason: item.reason,
              qty: 0,
            }));
          });
        } else {
          this.tableData.forEach((row) => {
            row.scrapItem = [];
          });
        }
      });
    },

    addDialogItem(row, item, flg) {
      //判断工序是否选择
      if (this.validatenull(this.form.processId)) {
        this.$message.warning("请先选择工序。");
        return;
      }
      this.currentRow = row;
      this.defectItems = JSON.parse(JSON.stringify(item));
      this.dialogFlg = flg;
      this.checkedReasons = [];
      // 根据数量大于0来初始化checkedReasons
      this.checkedReasons = this.defectItems
        .filter((item) => item.qty > 0)
        .map((item) => item.reason);
      this.addDialogVisible = true;
      if (flg === "bad") {
        this.addTitle = "不良添加";
        this.addReasonLabel = "不良项目";
        this.addQtyLabel = "不良数量";
      } else {
        this.addTitle = "报废添加";
        this.addReasonLabel = "报废项目";
        this.addQtyLabel = "报废数量";
      }
    },
    handleAddSubmit() {
      let totalQty = 0;
      const updatedDefectItems = this.defectItems.map((item) => {
        totalQty += item.qty;
        return {
          reason: item.reason,
          qty: this.checkedReasons.includes(item.reason) ? item.qty : 0,
        };
      });
      const rowIndex = this.tableData.findIndex(
        (r) =>
          r.startTime === this.currentRow.startTime &&
          r.endTime === this.currentRow.endTime
      );
      if (rowIndex !== -1) {
        if (this.dialogFlg === "bad") {
          this.tableData[rowIndex].badItem = updatedDefectItems;
          this.tableData[rowIndex].badQty = totalQty;
        } else {
          this.tableData[rowIndex].scrapItem = updatedDefectItems;
          this.tableData[rowIndex].scrapQty = totalQty;
        }
      }
      this.addDialogVisible = false;
    },
  },
};
</script>

<style scoped lang="less">
/deep/ .el-col {
  margin-bottom: 0px !important;
}

::v-deep .el-table th {
  background-color: #f6f8fa !important;
}

/deep/.el-form-item--mini.el-form-item,
.el-form-item--small.el-form-item {
  margin-bottom: 0px !important;
}
/* 为el-col添加边框样式，这里设置了四周的边框，你可以根据实际需求调整 */
.form-col {
  /* border: 1px solid #ebeef5; 边框颜色和粗细可根据喜好修改 */
  border-bottom: none;
  padding: 10px; /* 添加内边距让内容不紧贴边框，可调整 */
}

/* 使用相邻兄弟选择器去除相邻el-col之间重复的左边框 */
.form-col + .form-col {
  border-left: none;
  border-bottom: none;
}

/* 确保第一个el-col的左边框正常显示 */
.form-row.form-col:first-child {
  border-left: 1px solid #ebeef5;
  border-bottom: none;
}

/* 确保最后一个el-col的右边框正常显示，这里通过选择最后一个子元素来实现 */
.form-row.form-col:last-child {
  border-right: 1px solid #ebeef5;
  border-bottom: none;
}
.item-row {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}
/deep/.el-checkbox-button__inner {
  width: 100% !important;
  height: 40px !important;
  line-height: 20px !important;
}
.item-container {
  padding: 0 5px;
}
.item-container:last-child {
  border-bottom: none;
}
.custom-checkbox-button {
  width: 200px;
}
.item-row {
  display: flex;
  align-items: center;
  text-align: center;
}
.column-labels {
  display: flex;
  margin-bottom: 10px;
  font-weight: bold;
  position: sticky;
  top: 0; /* 距离顶部0像素，即固定在顶部 */
  background-color: white; /* 设置背景色，避免内容滚动时露出下面的内容 */
  z-index: 2; /* 设置层级，确保在内容上方 */
}
.label-item {
  flex: 1;
  text-align: center;
}
.dialog-form {
  height: 100%;
  overflow-y: auto; /* 添加垂直滚动条 */
  border: 1px solid #c0c4cc;
}
/* 隐藏滚动条 */
.dialog-form::-webkit-scrollbar {
  width: 0px;
  background: transparent;
}

.hander {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px 20px 20px;
  margin-bottom: 10px;
}
.tit {
  font-size: 18px;
  font-weight: 600;
}
.right {
  display: flex;
  align-items: center;
}
.name {
  margin-right: 10px;
  color: "#5a5a5a";
  font-size: 14px;
}
.out {
  cursor: pointer;
  color: #409eff;
  text-decoration: underline;
}
.bg-container {
  background-color: #f6f7fa;
}
.hander {
  background-color: #fff;
}
.form-data {
  background-color: #fff;
  margin: 10px;
}
.table-data {
  background-color: #fff;
  margin: 10px 10px 0 10px;
  padding: 10px 10px 0 10px;
  .info-t {
    display: flex;
    justify-content: space-between;
    align-items: center;
    .info-left {
      display: flex;
      align-items: center;
      height: 40px !important;
      line-height: 40px !important;
      margin-bottom: 10px;
      color: "#333";
      .item {
        // width: 120px;
        padding:0 20px;
        font-weight: 700;
      }
    }
    .info-right {
      display: flex;
      align-items: center;
      height: 40px !important;
      line-height: 40px !important;
      margin-bottom: 10px;
      color: "#333";
      .item {
        // width: 120px;
        padding:0 20px 0 0;
        font-weight: 700;
      }
    }
  }
}
.footer {
  height: 60px;
  line-height: 60px;
  width: 100%;
  position: fixed;
  bottom: 0;
  left: 0;
  z-index: 9999999;
  background-color: #fff;
  padding-left: 30px;
}
</style>
